import { execSync } from 'node:child_process';

import axios from 'axios';
import fs from 'fs';
import { format } from 'prettier';

const jsonStr = fs.readFileSync('./.apifox-info.json', 'utf-8');
const apifoxInfo = JSON.parse(jsonStr);

// 项目id
const PROJECT_ID = apifoxInfo.PROJECT_ID;
// 令牌
const ACCESS_TOKEN = apifoxInfo.ACCESS_TOKEN;
// 导出开放接口url
const APIFOX_EXPORT_URL = `https://api.apifox.com/v1/projects/${PROJECT_ID}/export-openapi?locale=zh-CN`;
// 生成产物路径
const OUTPUT_FILE_PATH = './node_modules/api-spec.json';
const OUTPUT_TS_DIR = './src/api/api.d.ts';

function getPrettierOptions() {
  let prettierOptions = {};
  if (fs.existsSync('.prettierrc')) {
    prettierOptions = JSON.parse(fs.readFileSync('.prettierrc').toString());
  }

  if (!prettierOptions.parser) {
    prettierOptions.parser = 'typescript';
  }

  return prettierOptions;
}

async function formatFile(filePath) {
  const code = fs.readFileSync(filePath).toString();
  try {
    const formattedCode = await format(code, getPrettierOptions());
    fs.writeFileSync(filePath, formattedCode);
    console.log(`Formatted ${filePath} successfully.`);
  } catch (error) {
    console.log(error);
  }
}

/** 获取openApi数据并保存文件到项目中 */
async function fetchAndSaveOpenApi() {
  try {
    const response = await axios.post(
      APIFOX_EXPORT_URL,
      {
        scope: {
          type: 'ALL',
          excludedByTags: []
        },
        options: {
          includeApifoxExtensionProperties: false,
          addFoldersToTags: false
        },
        oasVersion: '3.0',
        exportFormat: 'JSON'
      },
      {
        responseType: 'json',
        headers: {
          Authorization: `Bearer ${ACCESS_TOKEN}`,
          'X-Apifox-Api-Version': '2024-03-28'
        }
      }
    );

    fs.writeFileSync(OUTPUT_FILE_PATH, JSON.stringify(response.data, null, 2));
    console.log('Fetch OpenAPI specification successfully.');

  } catch (error) {
    console.error('Error fetching OpenAPI specification:', error);
  }
}

//调用插件提供的方法生成客户端ts代码
async function generateTypescript() {
  try {
    execSync(`openapi-typescript ${OUTPUT_FILE_PATH} --output ${OUTPUT_TS_DIR}`);
    formatFile(OUTPUT_TS_DIR);
    console.log('TypeScript files generated successfully.');
  } catch (error) {
    console.error('Error generating TypeScript files:', error);
  }
}

fetchAndSaveOpenApi().then(generateTypescript);
